package com.itheima.servlet;

import com.itheima.javaBean.User;
//
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class UserListServlet implements Servlet {


    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        //创建User类集合list
        ArrayList<User> list = new ArrayList<>();
        //将数据储存到集合
        list.add(new User("100", "张三", 20));
        list.add(new User("200", "李四", 22));
        list.add(new User("300", "王五", 18));
        list.add(new User("400", "赵六", 44));
        list.add(new User("500", "乾七", 24));
        //写入浏览器
        servletResponse.setContentType("text/html;charset=UTF-8");
        //返回字符打印流
        PrintWriter pw = servletResponse.getWriter();
        //新建StringBuder,凭借字符串
        StringBuilder sb = new StringBuilder();
        //写入表头
        sb.append("<div><table border=\"1\" align=\"center\" width=\"40%\">");
        //开始写入表格
        sb.append("<tr align=\"center\"><th>"+"编号"+"</th><th>"+"姓名"+"</th><th>"+"年龄"+"</th></tr>");
        //循环写入表格
        for (int i = 0; i < list.size(); i++) {
            User user = list.get(i);
            String id = user.getId();
            String name = user.getName();
            int age = user.getAge();
            sb.append("<tr align=\"center\"><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td></tr>");
        }
        //asb.束表格和段落
        sb.append("</table></div>");
        //输出字符串
        String s = sb.toString();
        //打印流输出
        pw.print(s);
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }

}
